package com.wryyyyy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wryyyyy.dto.Result;
import com.wryyyyy.entity.UserLabel;
import com.wryyyyy.mapper.UserLabelMapper;
import com.wryyyyy.service.IUserLabelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wryyyyy
 * @since 2023-11-12
 */
@Service
public class UserLabelServiceImpl extends ServiceImpl<UserLabelMapper, UserLabel> implements IUserLabelService {
    @Resource
    private UserLabelMapper userLabelMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Result choiceLabels(String userId, List<String> labelIds) {
        // 1.查询用户已经选择的标签
        List<String> beforeIds = userLabelMapper.selectLabelsByUser(userId);
        // 2.和新提交的标签进行比较
        List<String> add = CollectionUtil.subtractToList(labelIds, beforeIds);
        List<String> reduce = CollectionUtil.subtractToList(beforeIds, labelIds);
        // 3.增加
        for (String s : add) {
            UserLabel userLabel = new UserLabel();
            userLabel.setUserId(userId);
            userLabel.setLabelId(s);
            userLabelMapper.insert(userLabel);
        }
        // 4.删除
        for (String s : reduce) {
            UserLabel userLabel = query().eq("user_id",userId).eq("label_id",s).one();
            userLabelMapper.deleteById(userLabel.getId());
        }
        return Result.ok("保存成功");
    }
}